package com.lac.component.utils;

import com.aliyun.oss.OSS;

import com.aliyun.oss.OSSClientBuilder;

import com.aliyun.oss.model.ObjectMetadata;

import com.aliyun.oss.model.PutObjectRequest;



import java.io.BufferedInputStream;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.Date;

import java.util.UUID;



public class OSSUrlUploader {



    // OSS配置 pro

    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";

    private static final String ACCESS_KEY_ID = "LTAI4GCU28CXshv2qxBVNyEM";

    private static final String ACCESS_KEY_SECRET = "Q959PTnnQWpv0ZHAqC2szFC0BiGmFR";

    private static final String BUCKET_NAME = "wm-prod-b1";


//    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
//
//    private static final String ACCESS_KEY_ID = "LTAI4FkEXxdrFutaMx7qXAao";
//
//    private static final String ACCESS_KEY_SECRET = "TrjSk2L3NqxOoOH7iPnDrdV5kTDY7y";
//
//    private static final String BUCKET_NAME = "wm-dev-b1";


    /**

     * 从URL下载文件并上传到OSS，使用雪花算法生成随机文件名

     *

     * @param fileUrl 源文件URL

     * @param folder OSS存储目录 (e.g. "material")

     * @return 文件访问URL

     */

    public static String uploadFromUrlWithSnowflakeName(String fileUrl, String folder) {

        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        HttpURLConnection connection = null;



        try {

            // 1. 创建URL连接

            URL url = new URL(fileUrl);

            connection = (HttpURLConnection) url.openConnection();



            // 设置超时和请求属性

            connection.setConnectTimeout(30000);

            connection.setReadTimeout(60000);

            connection.setRequestProperty("User-Agent", "Mozilla/5.0");



            // 2. 获取文件信息

            int responseCode = connection.getResponseCode();

            if (responseCode != HttpURLConnection.HTTP_OK) {

                throw new RuntimeException("Failed to download file. HTTP code: " + responseCode);

            }



            // 3. 获取Content-Type和Content-Length

            String contentType = connection.getContentType();

            long contentLength = connection.getContentLengthLong();



            // 4. 提取文件扩展名

            String fileExtension = extractFileExtension(fileUrl);

            if (fileExtension == null && contentType != null) {

                fileExtension = getExtensionFromContentType(contentType);

            }

            if (fileExtension == null) {

                fileExtension = "dat"; // 默认扩展名

            }



            // 5. 生成雪花算法随机文件名（使用UUID模拟）

            String randomFileName = generateSnowflakeLikeFileName() + "." + fileExtension;

            String objectName = folder + "/" + randomFileName;



            // 6. 创建OSS元数据

            ObjectMetadata metadata = new ObjectMetadata();

            if (contentType != null) {

                metadata.setContentType(contentType);

            }

            if (contentLength > 0) {

                metadata.setContentLength(contentLength);

            }



            // 7. 创建输入流

            try (InputStream inputStream = new BufferedInputStream(connection.getInputStream())) {

                // 8. 创建OSS上传请求

                PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, objectName, inputStream, metadata);



                // 9. 执行上传

                ossClient.putObject(request);



                // 10. 生成访问URL（直接使用OSS格式，不生成预签名URL）

                return "https://" + BUCKET_NAME + "." + ENDPOINT.replace("https://", "") + "/" + objectName;

            }

        } catch (Exception e) {

            throw new RuntimeException("Error uploading from URL: " + fileUrl, e);

        } finally {

            // 11. 清理资源

            if (connection != null) {

                connection.disconnect();

            }

            if (ossClient != null) {

                ossClient.shutdown();

            }

        }

    }



    /**

     * 生成类似雪花算法的随机文件名（使用UUID模拟）

     * 格式：d195281f-c8da-4f55-b45f-4d21f2240ed7

     */

    private static String generateSnowflakeLikeFileName() {

        return UUID.randomUUID().toString().toLowerCase();

    }



    /**

     * 从URL中提取文件扩展名

     */

    private static String extractFileExtension(String fileUrl) {

        // 去除查询参数

        String baseUrl = fileUrl.split("\\?")[0];



        // 获取文件名部分

        int lastSlash = baseUrl.lastIndexOf('/');

        String fileName = (lastSlash >= 0) ? baseUrl.substring(lastSlash + 1) : baseUrl;



        // 提取扩展名

        int dotIndex = fileName.lastIndexOf('.');

        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {

            return fileName.substring(dotIndex + 1).toLowerCase();

        }

        return null;

    }



    /**

     * 根据Content-Type获取文件扩展名

     */

    private static String getExtensionFromContentType(String contentType) {

        // 去掉可能的分号后面的部分

        String mimeType = contentType.split(";")[0].trim().toLowerCase();



        switch (mimeType) {

            case "image/jpeg": return "jpg";

            case "image/png": return "png";

            case "image/gif": return "gif";

            case "image/webp": return "webp";

            case "application/pdf": return "pdf";

            case "application/msword": return "doc";

            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": return "docx";

            case "application/vnd.ms-excel": return "xls";

            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": return "xlsx";

            case "application/vnd.ms-powerpoint": return "ppt";

            case "application/vnd.openxmlformats-officedocument.presentationml.presentation": return "pptx";

            case "application/zip": return "zip";

            case "audio/mpeg": return "mp3";

            case "audio/wav": return "wav";

            case "video/mp4": return "mp4";

            case "video/quicktime": return "mov";

            case "text/plain": return "txt";

            case "text/html": return "html";

            default: return null;

        }

    }



    // 使用示例

    public static void main(String[] args) {

        String imageUrl = "https://video.laikang.com/aa63c4406d8f71eebfb46733a68f0102/57b1b54ce2734df6855c264e2882c71f-57786bf00a97ac2017baadb3669847ec-ld.mp4";

        String folder = "common/video";



        String resultUrl = uploadFromUrlWithSnowflakeName(imageUrl, folder);

        System.out.println("File uploaded to: " + resultUrl);

        // 输出示例: https://lk-joolun-pro.oss-cn-beijing.aliyuncs.com/material/d195281f-c8da-4f55-b45f-4d21f2240ed7.jpg

    }

}